/**
 * 用户认证管理器
 * 提供用户登录、注册、权限验证、会话管理等功能
 */

import { logInfo, logWarn, logError } from './errorHandler.js'
import { post, get, put } from './networkManager.js'
import { setCache, getCache, deleteCache } from './cacheManager.js'
import { setState, getState } from './stateManager.js'

/**
 * 用户状态枚举
 */
export const USER_STATUS = {
	GUEST: 'guest',
	LOGGED_IN: 'logged_in',
	LOGGING_IN: 'logging_in',
	LOGGING_OUT: 'logging_out',
	REGISTERING: 'registering',
	VERIFYING: 'verifying',
	SUSPENDED: 'suspended',
	BANNED: 'banned'
}

/**
 * 认证类型枚举
 */
export const AUTH_TYPES = {
	EMAIL: 'email',
	PHONE: 'phone',
	USERNAME: 'username',
	WECHAT: 'wechat',
	QQ: 'qq',
	WEIBO: 'weibo',
	GUEST: 'guest'
}

/**
 * 权限级别枚举
 */
export const PERMISSION_LEVELS = {
	GUEST: 0,
	USER: 1,
	VIP: 2,
	MODERATOR: 3,
	ADMIN: 4,
	SUPER_ADMIN: 5
}

/**
 * 会话状态枚举
 */
export const SESSION_STATUS = {
	ACTIVE: 'active',
	EXPIRED: 'expired',
	INVALID: 'invalid',
	REVOKED: 'revoked'
}

/**
 * 用户信息类
 */
class UserInfo {
	constructor(data = {}) {
		this.id = data.id || null
		this.username = data.username || ''
		this.email = data.email || ''
		this.phone = data.phone || ''
		this.avatar = data.avatar || ''
		this.nickname = data.nickname || ''
		this.gender = data.gender || 0 // 0: 未知, 1: 男, 2: 女
		this.birthday = data.birthday || null
		this.location = data.location || ''
		this.bio = data.bio || ''
		this.level = data.level || PERMISSION_LEVELS.USER
		this.vipLevel = data.vipLevel || 0
		this.points = data.points || 0
		this.coins = data.coins || 0
		this.experience = data.experience || 0
		this.achievements = data.achievements || []
		this.preferences = data.preferences || {}
		this.settings = data.settings || {}
		this.status = data.status || USER_STATUS.GUEST
		this.isVerified = data.isVerified || false
		this.isVip = data.isVip || false
		this.createdAt = data.createdAt || null
		this.lastLoginAt = data.lastLoginAt || null
		this.loginCount = data.loginCount || 0
		this.deviceInfo = data.deviceInfo || {}
		this.permissions = data.permissions || []
		this.roles = data.roles || []
		this.metadata = data.metadata || {}
	}
	
	/**
	 * 检查是否有指定权限
	 * @param {string} permission - 权限名称
	 * @returns {boolean} 是否有权限
	 */
	hasPermission(permission) {
		return this.permissions.includes(permission) || this.level >= PERMISSION_LEVELS.ADMIN
	}
	
	/**
	 * 检查是否有指定角色
	 * @param {string} role - 角色名称
	 * @returns {boolean} 是否有角色
	 */
	hasRole(role) {
		return this.roles.includes(role)
	}
	
	/**
	 * 检查权限级别
	 * @param {number} requiredLevel - 需要的权限级别
	 * @returns {boolean} 是否满足权限级别
	 */
	hasLevel(requiredLevel) {
		return this.level >= requiredLevel
	}
	
	/**
	 * 获取用户显示名称
	 * @returns {string} 显示名称
	 */
	getDisplayName() {
		return this.nickname || this.username || this.email || this.phone || '游客'
	}
	
	/**
	 * 获取用户头像URL
	 * @returns {string} 头像URL
	 */
	getAvatarUrl() {
		return this.avatar || '/static/images/default-avatar.png'
	}
	
	/**
	 * 更新用户信息
	 * @param {Object} data - 更新数据
	 */
	update(data) {
		Object.keys(data).forEach(key => {
			if (this.hasOwnProperty(key)) {
				this[key] = data[key]
			}
		})
	}
	
	/**
	 * 转换为普通对象
	 * @returns {Object} 普通对象
	 */
	toObject() {
		return {
			id: this.id,
			username: this.username,
			email: this.email,
			phone: this.phone,
			avatar: this.avatar,
			nickname: this.nickname,
			gender: this.gender,
			birthday: this.birthday,
			location: this.location,
			bio: this.bio,
			level: this.level,
			vipLevel: this.vipLevel,
			points: this.points,
			coins: this.coins,
			experience: this.experience,
			achievements: this.achievements,
			preferences: this.preferences,
			settings: this.settings,
			status: this.status,
			isVerified: this.isVerified,
			isVip: this.isVip,
			createdAt: this.createdAt,
			lastLoginAt: this.lastLoginAt,
			loginCount: this.loginCount,
			deviceInfo: this.deviceInfo,
			permissions: this.permissions,
			roles: this.roles,
			metadata: this.metadata
		}
	}
}

/**
 * 会话信息类
 */
class SessionInfo {
	constructor(data = {}) {
		this.token = data.token || ''
		this.refreshToken = data.refreshToken || ''
		this.expiresAt = data.expiresAt || 0
		this.refreshExpiresAt = data.refreshExpiresAt || 0
		this.createdAt = data.createdAt || Date.now()
		this.lastActiveAt = data.lastActiveAt || Date.now()
		this.deviceId = data.deviceId || ''
		this.deviceInfo = data.deviceInfo || {}
		this.ipAddress = data.ipAddress || ''
		this.userAgent = data.userAgent || ''
		this.status = data.status || SESSION_STATUS.ACTIVE
		this.metadata = data.metadata || {}
	}
	
	/**
	 * 检查会话是否有效
	 * @returns {boolean} 是否有效
	 */
	isValid() {
		return this.status === SESSION_STATUS.ACTIVE && 
			   this.expiresAt > Date.now()
	}
	
	/**
	 * 检查是否需要刷新
	 * @returns {boolean} 是否需要刷新
	 */
	needsRefresh() {
		const refreshThreshold = 5 * 60 * 1000 // 5分钟
		return this.expiresAt - Date.now() < refreshThreshold
	}
	
	/**
	 * 检查刷新token是否有效
	 * @returns {boolean} 刷新token是否有效
	 */
	canRefresh() {
		return this.refreshToken && this.refreshExpiresAt > Date.now()
	}
	
	/**
	 * 更新最后活跃时间
	 */
	updateLastActive() {
		this.lastActiveAt = Date.now()
	}
	
	/**
	 * 更新会话信息
	 * @param {Object} data - 更新数据
	 */
	update(data) {
		Object.keys(data).forEach(key => {
			if (this.hasOwnProperty(key)) {
				this[key] = data[key]
			}
		})
	}
	
	/**
	 * 转换为普通对象
	 * @returns {Object} 普通对象
	 */
	toObject() {
		return {
			token: this.token,
			refreshToken: this.refreshToken,
			expiresAt: this.expiresAt,
			refreshExpiresAt: this.refreshExpiresAt,
			createdAt: this.createdAt,
			lastActiveAt: this.lastActiveAt,
			deviceId: this.deviceId,
			deviceInfo: this.deviceInfo,
			ipAddress: this.ipAddress,
			userAgent: this.userAgent,
			status: this.status,
			metadata: this.metadata
		}
	}
}

/**
 * 认证管理器类
 */
class AuthManager {
	constructor() {
		// 当前用户信息
		this.currentUser = new UserInfo()
		
		// 当前会话信息
		this.currentSession = new SessionInfo()
		
		// 认证状态
		this.isAuthenticated = false
		this.isInitialized = false
		
		// 配置选项
		this.config = {
			apiBaseUrl: '/api/auth',
			tokenKey: 'auth_token',
			refreshTokenKey: 'refresh_token',
			userInfoKey: 'user_info',
			sessionKey: 'session_info',
			autoRefresh: true,
			refreshThreshold: 5 * 60 * 1000, // 5分钟
			maxRetries: 3,
			retryDelay: 1000,
			enableGuestMode: true,
			enableRememberMe: true,
			sessionTimeout: 24 * 60 * 60 * 1000, // 24小时
			refreshTokenTimeout: 7 * 24 * 60 * 60 * 1000, // 7天
			enableDeviceTracking: true,
			enableLocationTracking: false,
			enableSecurityLog: true,
			maxConcurrentSessions: 5
		}
		
		// 事件监听器
		this.listeners = {
			login: [],
			logout: [],
			register: [],
			userUpdate: [],
			sessionExpired: [],
			permissionDenied: [],
			errorOccurred: []
		}
		
		// 刷新定时器
		this.refreshTimer = null
		
		// 统计信息
		this.stats = {
			loginAttempts: 0,
			successfulLogins: 0,
			failedLogins: 0,
			logouts: 0,
			registrations: 0,
			tokenRefreshes: 0,
			permissionChecks: 0,
			sessionExpiries: 0,
			startTime: Date.now()
		}
		
		this.init()
	}
	
	/**
	 * 初始化认证管理器
	 */
	async init() {
		try {
			this.loadConfig()
			await this.loadStoredAuth()
			this.setupAutoRefresh()
			this.setupSessionMonitoring()
			
			this.isInitialized = true
			
			logInfo('认证管理器已初始化', {
				isAuthenticated: this.isAuthenticated,
				userId: this.currentUser.id,
				username: this.currentUser.username
			})
			
			// 验证当前会话
			if (this.isAuthenticated) {
				await this.validateSession()
			}
		} catch (error) {
			logError('认证管理器初始化失败', { error: error.message })
			this.handleAuthError(error)
		}
	}
	
	/**
	 * 加载配置
	 */
	loadConfig() {
		try {
			if (typeof uni !== 'undefined') {
				const saved = uni.getStorageSync('auth_config')
				if (saved) {
					this.config = { ...this.config, ...saved }
				}
			}
		} catch (error) {
			logError('加载认证配置失败', { error: error.message })
		}
	}
	
	/**
	 * 保存配置
	 */
	saveConfig() {
		try {
			if (typeof uni !== 'undefined') {
				uni.setStorageSync('auth_config', this.config)
			}
		} catch (error) {
			logError('保存认证配置失败', { error: error.message })
		}
	}
	
	/**
	 * 加载存储的认证信息
	 */
	async loadStoredAuth() {
		try {
			if (typeof uni !== 'undefined') {
				// 加载用户信息
				const userInfo = uni.getStorageSync(this.config.userInfoKey)
				if (userInfo) {
					this.currentUser = new UserInfo(userInfo)
				}
				
				// 加载会话信息
				const sessionInfo = uni.getStorageSync(this.config.sessionKey)
				if (sessionInfo) {
					this.currentSession = new SessionInfo(sessionInfo)
				}
				
				// 检查认证状态
				if (this.currentSession.isValid() && this.currentUser.id) {
					this.isAuthenticated = true
					this.updateUserState()
				} else {
					// 清除无效的认证信息
					this.clearStoredAuth()
				}
			}
		} catch (error) {
			logError('加载存储认证信息失败', { error: error.message })
			this.clearStoredAuth()
		}
	}
	
	/**
	 * 保存认证信息到存储
	 */
	saveAuthToStorage() {
		try {
			if (typeof uni !== 'undefined') {
				uni.setStorageSync(this.config.tokenKey, this.currentSession.token)
				uni.setStorageSync(this.config.refreshTokenKey, this.currentSession.refreshToken)
				uni.setStorageSync(this.config.userInfoKey, this.currentUser.toObject())
				uni.setStorageSync(this.config.sessionKey, this.currentSession.toObject())
			}
		} catch (error) {
			logError('保存认证信息失败', { error: error.message })
		}
	}
	
	/**
	 * 清除存储的认证信息
	 */
	clearStoredAuth() {
		try {
			if (typeof uni !== 'undefined') {
				uni.removeStorageSync(this.config.tokenKey)
				uni.removeStorageSync(this.config.refreshTokenKey)
				uni.removeStorageSync(this.config.userInfoKey)
				uni.removeStorageSync(this.config.sessionKey)
			}
		} catch (error) {
			logError('清除认证信息失败', { error: error.message })
		}
	}
	
	/**
	 * 用户登录
	 * @param {Object} credentials - 登录凭据
	 * @param {Object} options - 选项
	 * @returns {Promise<UserInfo>} 用户信息
	 */
	async login(credentials, options = {}) {
		try {
			this.stats.loginAttempts++
			
			// 设置登录状态
			this.currentUser.status = USER_STATUS.LOGGING_IN
			this.updateUserState()
			
			// 准备登录数据
			const loginData = {
				...credentials,
				deviceInfo: this.getDeviceInfo(),
				rememberMe: options.rememberMe || false,
				loginType: options.loginType || AUTH_TYPES.EMAIL
			}
			
			// 发送登录请求
			const response = await post(`${this.config.apiBaseUrl}/login`, loginData, {
				timeout: 10000,
				retries: this.config.maxRetries
			})
			
			if (response.data.success) {
				// 更新用户信息
				this.currentUser = new UserInfo(response.data.user)
				this.currentUser.status = USER_STATUS.LOGGED_IN
				
				// 更新会话信息
				this.currentSession = new SessionInfo({
					token: response.data.token,
					refreshToken: response.data.refreshToken,
					expiresAt: Date.now() + this.config.sessionTimeout,
					refreshExpiresAt: Date.now() + this.config.refreshTokenTimeout,
					deviceId: this.getDeviceId(),
					deviceInfo: this.getDeviceInfo()
				})
				
				// 设置认证状态
				this.isAuthenticated = true
				
				// 保存到存储
				this.saveAuthToStorage()
				
				// 更新状态管理器
				this.updateUserState()
				
				// 设置自动刷新
				this.setupAutoRefresh()
				
				// 更新统计
				this.stats.successfulLogins++
				
				// 触发登录事件
				this.emit('login', this.currentUser)
				
				logInfo('用户登录成功', {
					userId: this.currentUser.id,
					username: this.currentUser.username,
					loginType: loginData.loginType
				})
				
				return this.currentUser
			} else {
				throw new Error(response.data.message || '登录失败')
			}
		} catch (error) {
			this.stats.failedLogins++
			this.currentUser.status = USER_STATUS.GUEST
			this.updateUserState()
			
			logError('用户登录失败', {
				error: error.message,
				credentials: { ...credentials, password: '***' }
			})
			
			this.emit('errorOccurred', error)
			throw error
		}
	}
	
	/**
	 * 微信登录
	 * @param {Object} wechatData - 微信登录数据
	 * @returns {Promise<UserInfo>} 用户信息
	 */
	async wechatLogin(wechatData) {
		try {
			this.stats.loginAttempts++
			
			// 设置登录状态
			this.currentUser.status = USER_STATUS.LOGGING_IN
			this.updateUserState()
			
			// 准备微信登录数据
			const loginData = {
				code: wechatData.code,
				userInfo: wechatData.userInfo,
				deviceInfo: this.getDeviceInfo()
			}
			
			// 发送微信登录请求
			const response = await post(`${this.config.apiBaseUrl}/wechat/login`, loginData, {
				timeout: 10000,
				retries: this.config.maxRetries
			})
			
			if (response.data.success) {
				// 更新用户信息
				this.currentUser = new UserInfo({
					id: response.data.userId,
					username: wechatData.userInfo.nickName,
					nickname: wechatData.userInfo.nickName,
					avatar: wechatData.userInfo.avatarUrl,
					gender: wechatData.userInfo.gender,
					location: `${wechatData.userInfo.country} ${wechatData.userInfo.province} ${wechatData.userInfo.city}`.trim(),
					status: USER_STATUS.LOGGED_IN
				})
				
				// 更新会话信息
				this.currentSession = new SessionInfo({
					token: response.data.data,
					expiresAt: Date.now() + this.config.sessionTimeout,
					deviceId: this.getDeviceId(),
					deviceInfo: this.getDeviceInfo()
				})
				
				// 设置认证状态
				this.isAuthenticated = true
				
				// 保存到存储
				this.saveAuthToStorage()
				
				// 更新状态管理器
				this.updateUserState()
				
				// 设置自动刷新
				this.setupAutoRefresh()
				
				// 更新统计
				this.stats.successfulLogins++
				
				// 触发登录事件
				this.emit('login', this.currentUser)
				
				logInfo('微信登录成功', {
					userId: this.currentUser.id,
					nickname: this.currentUser.nickname
				})
				
				return this.currentUser
			} else {
				throw new Error(response.data.message || '微信登录失败')
			}
		} catch (error) {
			this.stats.failedLogins++
			this.currentUser.status = USER_STATUS.GUEST
			this.updateUserState()
			
			logError('微信登录失败', {
				error: error.message,
				wechatData: { ...wechatData, userInfo: { ...wechatData.userInfo, code: '***' } }
			})
			
			this.emit('errorOccurred', error)
			throw error
		}
	}
	
	/**
	 * 用户注册
	 * @param {Object} userData - 用户数据
	 * @param {Object} options - 选项
	 * @returns {Promise<UserInfo>} 用户信息
	 */
	async register(userData, options = {}) {
		try {
			// 设置注册状态
			this.currentUser.status = USER_STATUS.REGISTERING
			this.updateUserState()
			
			// 准备注册数据
			const registerData = {
				...userData,
				deviceInfo: this.getDeviceInfo(),
				registerType: options.registerType || AUTH_TYPES.EMAIL,
				autoLogin: options.autoLogin !== false
			}
			
			// 发送注册请求
			const response = await post(`${this.config.apiBaseUrl}/register`, registerData, {
				timeout: 15000,
				retries: this.config.maxRetries
			})
			
			if (response.data.success) {
				// 更新统计
				this.stats.registrations++
				
				// 如果自动登录
				if (registerData.autoLogin && response.data.token) {
					// 更新用户信息
					this.currentUser = new UserInfo(response.data.user)
					this.currentUser.status = USER_STATUS.LOGGED_IN
					
					// 更新会话信息
					this.currentSession = new SessionInfo({
						token: response.data.token,
						refreshToken: response.data.refreshToken,
						expiresAt: Date.now() + this.config.sessionTimeout,
						refreshExpiresAt: Date.now() + this.config.refreshTokenTimeout,
						deviceId: this.getDeviceId(),
						deviceInfo: this.getDeviceInfo()
					})
					
					// 设置认证状态
					this.isAuthenticated = true
					
					// 保存到存储
					this.saveAuthToStorage()
					
					// 设置自动刷新
					this.setupAutoRefresh()
				} else {
					// 只更新用户信息，不登录
					this.currentUser = new UserInfo(response.data.user)
					this.currentUser.status = USER_STATUS.GUEST
				}
				
				// 更新状态管理器
				this.updateUserState()
				
				// 触发注册事件
				this.emit('register', this.currentUser)
				
				logInfo('用户注册成功', {
					userId: this.currentUser.id,
					username: this.currentUser.username,
					registerType: registerData.registerType,
					autoLogin: registerData.autoLogin
				})
				
				return this.currentUser
			} else {
				throw new Error(response.data.message || '注册失败')
			}
		} catch (error) {
			this.currentUser.status = USER_STATUS.GUEST
			this.updateUserState()
			
			logError('用户注册失败', {
				error: error.message,
				userData: { ...userData, password: '***' }
			})
			
			this.emit('errorOccurred', error)
			throw error
		}
	}
	
	/**
	 * 用户登出
	 * @param {Object} options - 选项
	 * @returns {Promise<boolean>} 是否成功
	 */
	async logout(options = {}) {
		try {
			// 设置登出状态
			this.currentUser.status = USER_STATUS.LOGGING_OUT
			this.updateUserState()
			
			// 如果需要通知服务器
			if (options.notifyServer !== false && this.currentSession.token) {
				try {
					await post(`${this.config.apiBaseUrl}/logout`, {
						token: this.currentSession.token,
						deviceId: this.getDeviceId()
					}, {
						timeout: 5000
					})
				} catch (error) {
					logWarn('通知服务器登出失败', { error: error.message })
				}
			}
			
			// 清除认证信息
			this.clearAuth()
			
			// 更新统计
			this.stats.logouts++
			
			// 触发登出事件
			this.emit('logout')
			
			logInfo('用户登出成功')
			
			return true
		} catch (error) {
			logError('用户登出失败', { error: error.message })
			this.emit('errorOccurred', error)
			return false
		}
	}
	
	/**
	 * 清除认证信息
	 */
	clearAuth() {
		// 清除定时器
		if (this.refreshTimer) {
			clearTimeout(this.refreshTimer)
			this.refreshTimer = null
		}
		
		// 重置用户信息
		this.currentUser = new UserInfo()
		this.currentUser.status = USER_STATUS.GUEST
		
		// 重置会话信息
		this.currentSession = new SessionInfo()
		
		// 设置认证状态
		this.isAuthenticated = false
		
		// 清除存储
		this.clearStoredAuth()
		
		// 清除缓存
		deleteCache('user_profile')
		deleteCache('user_permissions')
		
		// 更新状态管理器
		this.updateUserState()
	}
	
	/**
	 * 刷新访问令牌
	 * @returns {Promise<boolean>} 是否成功
	 */
	async refreshToken() {
		try {
			if (!this.currentSession.canRefresh()) {
				throw new Error('无法刷新令牌')
			}
			
			const response = await post(`${this.config.apiBaseUrl}/refresh`, {
				refreshToken: this.currentSession.refreshToken,
				deviceId: this.getDeviceId()
			}, {
				timeout: 10000
			})
			
			if (response.data.success) {
				// 更新会话信息
				this.currentSession.update({
					token: response.data.token,
					refreshToken: response.data.refreshToken || this.currentSession.refreshToken,
					expiresAt: Date.now() + this.config.sessionTimeout,
					refreshExpiresAt: response.data.refreshToken 
						? Date.now() + this.config.refreshTokenTimeout 
						: this.currentSession.refreshExpiresAt
				})
				
				// 保存到存储
				this.saveAuthToStorage()
				
				// 更新统计
				this.stats.tokenRefreshes++
				
				// 设置下次刷新
				this.setupAutoRefresh()
				
				logInfo('令牌刷新成功')
				return true
			} else {
				throw new Error(response.data.message || '令牌刷新失败')
			}
		} catch (error) {
			logError('令牌刷新失败', { error: error.message })
			
			// 刷新失败，清除认证信息
			this.handleSessionExpired()
			return false
		}
	}
	
	/**
	 * 验证当前会话
	 * @returns {Promise<boolean>} 是否有效
	 */
	async validateSession() {
		try {
			if (!this.currentSession.isValid()) {
				return false
			}
			
			const response = await get(`${this.config.apiBaseUrl}/validate`, {
				headers: {
					Authorization: `Bearer ${this.currentSession.token}`
				},
				timeout: 5000
			})
			
			if (response.data.success) {
				// 更新用户信息
				if (response.data.user) {
					this.currentUser.update(response.data.user)
					this.updateUserState()
				}
				
				// 更新最后活跃时间
				this.currentSession.updateLastActive()
				this.saveAuthToStorage()
				
				return true
			} else {
				throw new Error('会话验证失败')
			}
		} catch (error) {
			logWarn('会话验证失败', { error: error.message })
			
			// 尝试刷新令牌
			if (this.currentSession.canRefresh()) {
				return await this.refreshToken()
			} else {
				this.handleSessionExpired()
				return false
			}
		}
	}
	
	/**
	 * 处理会话过期
	 */
	handleSessionExpired() {
		logWarn('会话已过期')
		
		// 更新统计
		this.stats.sessionExpiries++
		
		// 清除认证信息
		this.clearAuth()
		
		// 触发会话过期事件
		this.emit('sessionExpired')
	}
	
	/**
	 * 设置自动刷新
	 */
	setupAutoRefresh() {
		if (!this.config.autoRefresh || !this.isAuthenticated) {
			return
		}
		
		// 清除现有定时器
		if (this.refreshTimer) {
			clearTimeout(this.refreshTimer)
		}
		
		// 计算刷新时间
		const refreshTime = this.currentSession.expiresAt - Date.now() - this.config.refreshThreshold
		
		if (refreshTime > 0) {
			this.refreshTimer = setTimeout(async () => {
				if (this.isAuthenticated && this.currentSession.needsRefresh()) {
					await this.refreshToken()
				}
			}, refreshTime)
		}
	}
	
	/**
	 * 设置会话监控
	 */
	setupSessionMonitoring() {
		// 监听页面可见性变化
		if (typeof document !== 'undefined') {
			document.addEventListener('visibilitychange', () => {
				if (!document.hidden && this.isAuthenticated) {
					// 页面变为可见时验证会话
					this.validateSession()
				}
			})
		}
		
		// 监听应用前后台切换（uni-app）
		if (typeof uni !== 'undefined') {
			uni.onAppShow(() => {
				if (this.isAuthenticated) {
					this.validateSession()
				}
			})
		}
	}
	
	/**
	 * 更新用户信息
	 * @param {Object} userData - 用户数据
	 * @returns {Promise<UserInfo>} 更新后的用户信息
	 */
	async updateUserInfo(userData) {
		try {
			const response = await put(`${this.config.apiBaseUrl}/profile`, userData, {
				headers: {
					Authorization: `Bearer ${this.currentSession.token}`
				},
				timeout: 10000
			})
			
			if (response.data.success) {
				// 更新本地用户信息
				this.currentUser.update(response.data.user)
				
				// 保存到存储
				this.saveAuthToStorage()
				
				// 更新状态管理器
				this.updateUserState()
				
				// 触发用户更新事件
				this.emit('userUpdate', this.currentUser)
				
				logInfo('用户信息更新成功', { userId: this.currentUser.id })
				
				return this.currentUser
			} else {
				throw new Error(response.data.message || '更新用户信息失败')
			}
		} catch (error) {
			logError('更新用户信息失败', { error: error.message })
			this.emit('errorOccurred', error)
			throw error
		}
	}
	
	/**
	 * 修改密码
	 * @param {string} oldPassword - 旧密码
	 * @param {string} newPassword - 新密码
	 * @returns {Promise<boolean>} 是否成功
	 */
	async changePassword(oldPassword, newPassword) {
		try {
			const response = await put(`${this.config.apiBaseUrl}/password`, {
				oldPassword,
				newPassword
			}, {
				headers: {
					Authorization: `Bearer ${this.currentSession.token}`
				},
				timeout: 10000
			})
			
			if (response.data.success) {
				logInfo('密码修改成功', { userId: this.currentUser.id })
				return true
			} else {
				throw new Error(response.data.message || '密码修改失败')
			}
		} catch (error) {
			logError('密码修改失败', { error: error.message })
			this.emit('errorOccurred', error)
			throw error
		}
	}
	
	/**
	 * 检查权限
	 * @param {string|Array} permissions - 权限名称或数组
	 * @returns {boolean} 是否有权限
	 */
	hasPermission(permissions) {
		this.stats.permissionChecks++
		
		if (!this.isAuthenticated) {
			return false
		}
		
		if (Array.isArray(permissions)) {
			return permissions.every(permission => this.currentUser.hasPermission(permission))
		} else {
			return this.currentUser.hasPermission(permissions)
		}
	}
	
	/**
	 * 检查角色
	 * @param {string|Array} roles - 角色名称或数组
	 * @returns {boolean} 是否有角色
	 */
	hasRole(roles) {
		if (!this.isAuthenticated) {
			return false
		}
		
		if (Array.isArray(roles)) {
			return roles.some(role => this.currentUser.hasRole(role))
		} else {
			return this.currentUser.hasRole(roles)
		}
	}
	
	/**
	 * 检查权限级别
	 * @param {number} requiredLevel - 需要的权限级别
	 * @returns {boolean} 是否满足权限级别
	 */
	hasLevel(requiredLevel) {
		if (!this.isAuthenticated) {
			return false
		}
		
		return this.currentUser.hasLevel(requiredLevel)
	}
	
	/**
	 * 权限守卫
	 * @param {string|Array} permissions - 权限要求
	 * @param {Object} options - 选项
	 * @returns {boolean} 是否通过
	 */
	guard(permissions, options = {}) {
		const hasPermission = this.hasPermission(permissions)
		
		if (!hasPermission) {
			logWarn('权限检查失败', {
				requiredPermissions: permissions,
				userPermissions: this.currentUser.permissions,
				userLevel: this.currentUser.level
			})
			
			// 触发权限拒绝事件
			this.emit('permissionDenied', { permissions, user: this.currentUser })
			
			// 如果需要跳转到登录页
			if (options.redirectToLogin && !this.isAuthenticated) {
				this.redirectToLogin()
			}
		}
		
		return hasPermission
	}
	
	/**
	 * 跳转到登录页
	 */
	redirectToLogin() {
		try {
			if (typeof uni !== 'undefined') {
				uni.navigateTo({
					url: '/pages/auth/login'
				})
			} else if (typeof window !== 'undefined') {
				window.location.href = '/login'
			}
		} catch (error) {
			logError('跳转登录页失败', { error: error.message })
		}
	}
	
	/**
	 * 获取设备信息
	 * @returns {Object} 设备信息
	 */
	getDeviceInfo() {
		const deviceInfo = {
			timestamp: Date.now(),
			timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
			language: 'zh-CN'
		}
		
		try {
			if (typeof uni !== 'undefined') {
				const systemInfo = uni.getSystemInfoSync()
				deviceInfo.platform = systemInfo.platform
				deviceInfo.system = systemInfo.system
				deviceInfo.version = systemInfo.version
				deviceInfo.model = systemInfo.model
				deviceInfo.brand = systemInfo.brand
				deviceInfo.screenWidth = systemInfo.screenWidth
				deviceInfo.screenHeight = systemInfo.screenHeight
				deviceInfo.pixelRatio = systemInfo.pixelRatio
			} else if (typeof navigator !== 'undefined') {
				deviceInfo.platform = 'web'
				deviceInfo.userAgent = navigator.userAgent
				deviceInfo.language = navigator.language
				deviceInfo.screenWidth = screen.width
				deviceInfo.screenHeight = screen.height
				deviceInfo.pixelRatio = window.devicePixelRatio
			}
		} catch (error) {
			logWarn('获取设备信息失败', { error: error.message })
		}
		
		return deviceInfo
	}
	
	/**
	 * 获取设备ID
	 * @returns {string} 设备ID
	 */
	getDeviceId() {
		try {
			if (typeof uni !== 'undefined') {
				let deviceId = uni.getStorageSync('device_id')
				if (!deviceId) {
					deviceId = `device_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
					uni.setStorageSync('device_id', deviceId)
				}
				return deviceId
			} else {
				let deviceId = localStorage.getItem('device_id')
				if (!deviceId) {
					deviceId = `web_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
					localStorage.setItem('device_id', deviceId)
				}
				return deviceId
			}
		} catch {
			return `temp_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
		}
	}
	
	/**
	 * 更新用户状态到状态管理器
	 */
	updateUserState() {
		setState('user', {
			isAuthenticated: this.isAuthenticated,
			userInfo: this.currentUser.toObject(),
			sessionInfo: {
				isValid: this.currentSession.isValid(),
				expiresAt: this.currentSession.expiresAt,
				lastActiveAt: this.currentSession.lastActiveAt
			}
		})
	}
	
	/**
	 * 处理认证错误
	 * @param {Error} error - 错误对象
	 */
	handleAuthError(error) {
		if (error.response) {
			switch (error.response.status) {
				case 401:
					// 未授权，清除认证信息
					this.handleSessionExpired()
					break
				case 403:
					// 禁止访问
					this.emit('permissionDenied', { error })
					break
				case 429:
					// 请求过于频繁
					logWarn('请求过于频繁，请稍后再试')
					break
			}
		}
		
		this.emit('errorOccurred', error)
	}
	
	/**
	 * 添加事件监听器
	 * @param {string} event - 事件名称
	 * @param {Function} listener - 监听器函数
	 * @returns {Function} 移除监听器的函数
	 */
	on(event, listener) {
		if (this.listeners[event]) {
			this.listeners[event].push(listener)
			
			// 返回移除监听器的函数
			return () => {
				const index = this.listeners[event].indexOf(listener)
				if (index > -1) {
					this.listeners[event].splice(index, 1)
				}
			}
		}
		
		return () => {}
	}
	
	/**
	 * 移除事件监听器
	 * @param {string} event - 事件名称
	 * @param {Function} listener - 监听器函数
	 */
	off(event, listener) {
		if (this.listeners[event]) {
			const index = this.listeners[event].indexOf(listener)
			if (index > -1) {
				this.listeners[event].splice(index, 1)
			}
		}
	}
	
	/**
	 * 触发事件
	 * @param {string} event - 事件名称
	 * @param {*} data - 事件数据
	 */
	emit(event, data) {
		if (this.listeners[event]) {
			this.listeners[event].forEach(listener => {
				try {
					listener(data)
				} catch (error) {
					logError('事件监听器执行失败', {
						event,
						error: error.message
					})
				}
			})
		}
	}
	
	/**
	 * 获取认证统计信息
	 * @returns {Object} 统计信息
	 */
	getStats() {
		return {
			...this.stats,
			uptime: Date.now() - this.stats.startTime,
			successRate: this.stats.loginAttempts > 0 
				? (this.stats.successfulLogins / this.stats.loginAttempts * 100).toFixed(2) + '%'
				: '0%',
			currentUser: this.currentUser.getDisplayName(),
			isAuthenticated: this.isAuthenticated,
			sessionValid: this.currentSession.isValid()
		}
	}
	
	/**
	 * 重置统计信息
	 */
	resetStats() {
		this.stats = {
			loginAttempts: 0,
			successfulLogins: 0,
			failedLogins: 0,
			logouts: 0,
			registrations: 0,
			tokenRefreshes: 0,
			permissionChecks: 0,
			sessionExpiries: 0,
			startTime: Date.now()
		}
	}
	
	/**
	 * 更新配置
	 * @param {Object} newConfig - 新配置
	 */
	updateConfig(newConfig) {
		this.config = { ...this.config, ...newConfig }
		this.saveConfig()
		
		// 如果更新了自动刷新配置，重新设置
		if (newConfig.hasOwnProperty('autoRefresh') || newConfig.hasOwnProperty('refreshThreshold')) {
			this.setupAutoRefresh()
		}
	}
	
	/**
	 * 获取当前配置
	 * @returns {Object} 配置对象
	 */
	getConfig() {
		return { ...this.config }
	}
	
	/**
	 * 销毁认证管理器
	 */
	destroy() {
		// 清除定时器
		if (this.refreshTimer) {
			clearTimeout(this.refreshTimer)
			this.refreshTimer = null
		}
		
		// 清除事件监听器
		Object.keys(this.listeners).forEach(event => {
			this.listeners[event] = []
		})
		
		// 保存配置
		this.saveConfig()
		
		logInfo('认证管理器已销毁')
	}
}

// 创建全局实例
const authManager = new AuthManager()

// 导出便捷函数

/**
 * 用户登录
 * @param {Object} credentials - 登录凭据
 * @param {Object} options - 选项
 * @returns {Promise<UserInfo>} 用户信息
 */
export const login = (credentials, options) => authManager.login(credentials, options)

/**
 * 微信登录
 * @param {Object} wechatData - 微信登录数据
 * @returns {Promise<UserInfo>} 用户信息
 */
export const wechatLogin = (wechatData) => authManager.wechatLogin(wechatData)

/**
 * 用户注册
 * @param {Object} userData - 用户数据
 * @param {Object} options - 选项
 * @returns {Promise<UserInfo>} 用户信息
 */
export const register = (userData, options) => authManager.register(userData, options)

/**
 * 用户登出
 * @param {Object} options - 选项
 * @returns {Promise<boolean>} 是否成功
 */
export const logout = (options) => authManager.logout(options)

/**
 * 刷新访问令牌
 * @returns {Promise<boolean>} 是否成功
 */
export const refreshToken = () => authManager.refreshToken()

/**
 * 验证当前会话
 * @returns {Promise<boolean>} 是否有效
 */
export const validateSession = () => authManager.validateSession()

/**
 * 更新用户信息
 * @param {Object} userData - 用户数据
 * @returns {Promise<UserInfo>} 更新后的用户信息
 */
export const updateUserInfo = (userData) => authManager.updateUserInfo(userData)

/**
 * 修改密码
 * @param {string} oldPassword - 旧密码
 * @param {string} newPassword - 新密码
 * @returns {Promise<boolean>} 是否成功
 */
export const changePassword = (oldPassword, newPassword) => authManager.changePassword(oldPassword, newPassword)

/**
 * 检查权限
 * @param {string|Array} permissions - 权限名称或数组
 * @returns {boolean} 是否有权限
 */
export const hasPermission = (permissions) => authManager.hasPermission(permissions)

/**
 * 检查角色
 * @param {string|Array} roles - 角色名称或数组
 * @returns {boolean} 是否有角色
 */
export const hasRole = (roles) => authManager.hasRole(roles)

/**
 * 检查权限级别
 * @param {number} requiredLevel - 需要的权限级别
 * @returns {boolean} 是否满足权限级别
 */
export const hasLevel = (requiredLevel) => authManager.hasLevel(requiredLevel)

/**
 * 权限守卫
 * @param {string|Array} permissions - 权限要求
 * @param {Object} options - 选项
 * @returns {boolean} 是否通过
 */
export const guard = (permissions, options) => authManager.guard(permissions, options)

/**
 * 获取当前用户信息
 * @returns {UserInfo} 用户信息
 */
export const getCurrentUser = () => authManager.currentUser

/**
 * 获取当前会话信息
 * @returns {SessionInfo} 会话信息
 */
export const getCurrentSession = () => authManager.currentSession

/**
 * 检查是否已认证
 * @returns {boolean} 是否已认证
 */
export const isAuthenticated = () => authManager.isAuthenticated

/**
 * 添加事件监听器
 * @param {string} event - 事件名称
 * @param {Function} listener - 监听器函数
 * @returns {Function} 移除监听器的函数
 */
export const on = (event, listener) => authManager.on(event, listener)

/**
 * 移除事件监听器
 * @param {string} event - 事件名称
 * @param {Function} listener - 监听器函数
 */
export const off = (event, listener) => authManager.off(event, listener)

/**
 * 获取认证统计信息
 * @returns {Object} 统计信息
 */
export const getAuthStats = () => authManager.getStats()

/**
 * 重置统计信息
 */
export const resetAuthStats = () => authManager.resetStats()

/**
 * 更新配置
 * @param {Object} newConfig - 新配置
 */
export const updateAuthConfig = (newConfig) => authManager.updateConfig(newConfig)

/**
 * 获取当前配置
 * @returns {Object} 配置对象
 */
export const getAuthConfig = () => authManager.getConfig()

// 导出类和枚举
export {
	UserInfo,
	SessionInfo,
	AuthManager
}

// 导出默认实例
export default authManager